<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import FooterComp from '../components/FooterComp.vue';
import HeaderDemo from '../components/HeaderDemo.vue';
import axios from 'axios';
import CryptoJS from 'crypto-js';
import { ElMessageBox  } from 'element-plus';
// 现有变量
const title = ref('《箭指苍穹》');
const playwright = ref('刘群芳');
const tags = ref('现实主义, 导弹, 航天');
const playwrightBio = ref('刘群芳是一位著名剧作家，代表作《迷梦苍穹》已备案。');
const synopsis = ref('《箭指苍穹》是一部反映中国航天事业发展的剧本。');
const authorIntent = ref('作者希望通过该剧本传播中国航天精神。');
const uid = ref(1);
const jubenID = ref(11);
const workimg = ref('');
const wddataContent = ref(''); // 存储作品内容
//创作天数变量
const days = ref(0);

const route = useRoute();
const router = useRouter();
//定义作品数量
const totalWorksCount = ref(0);
//用户id
const luid = ref(1);
// 更新时间
const updateTime = ref('');

const totalWordsCount = ref(0); // 保存累计字数
//保存其他作品列表
const otherWorks = ref([]);

const navigateToWork = (wid) => {
  router.push({ path: `/workprofile/${wid}` }).then(() => {
    window.location.reload();
  });
};

// 解密token
function getToken() {
    const encryptedToken = localStorage.getItem('token');
    if (encryptedToken) {
        const secretKey = 'your_secret_key'; // 使用相同的密钥
        const bytes = CryptoJS.AES.decrypt(encryptedToken, secretKey);
        const decryptedToken = bytes.toString(CryptoJS.enc.Utf8);
        return decryptedToken;
    }
    return null;
}

// 获取脚本信息并处理 wddata
const getScriptInfo = async (id) => {
  try {
    const response = await axios.get(`http://localhost:8080/api/getwork/` + id);

    // 设置作品的基本信息
    title.value = response.data.wname;
    playwright.value = response.data.uname;
    playwrightBio.value = response.data.screenwriterBio;
    synopsis.value = response.data.introduction;
    uid.value = response.data.uid;
    authorIntent.value = response.data.money != null ? response.data.money : '编剧没有设置金额';
    workimg.value = response.data.wimage;

    // 设置更新时间
    updateTime.value = response.data.wnowdate; // 提取 wnowdate 并赋值给 updateTime

    // 获取并解码 wddata
    if (response.data.wddata) {
      console.log("原始数据："+response.data.wddata);
      // const decodedWddata = decodeUnicode(response.data.wddata);  // 解码 wddata
       // 提取前 1000 个字符
      // const trimmedWddata = decodedWddata.substring(0, 1000);  // 或者使用 decodedWddata.slice(0, 1000);
      wddataContent.value = response.data.wddata.substring(0,1000);  // 将解码后的数据赋值给 wddataContent
    }
  } catch (error) {
    console.error('获取脚本信息时出错:', error);
  }
};


// // 获取作者的其他作品
const fetchOtherWorks = async (currentWid) => {
  try {
    const response = await axios.get(`http://localhost:8080/api/getWordByWID/` + currentWid);
    console.log('获取到的所有作品数据:', response.data);

    if (response.data && Array.isArray(response.data.data)) {
      // 过滤掉当前作品，并提取其他作品的信息
      console.log("&&&&&&&&&&&&&&&&&&&&&&&&&&&&" + JSON.stringify(response.data, null, 2));
      // 获取作品总数
      const totalWorks = response.data.data.length;
      totalWorksCount.value = totalWorks; // 将总数赋值给 totalWorksCount
      // 计算累计字数
      const totalWords = response.data.data.reduce((sum, work) => {
        // 假设作品内容在 work.content 中，并计算其长度
        return sum + (work.wddata ? work.wddata.length : 0);
      }, 0);
      totalWordsCount.value = totalWords; // 将累计字数赋值给 totalWordsCount

      console.log('作品总数:', totalWorks); // 输出作品总数
      console.log('累计字数:', totalWords); // 输出累计字数
      otherWorks.value = response.data.data
      console.log('过滤后的其他作品:', otherWorks.value)

        .filter((work) => {
          console.log(`检查作品: UID=${work.uid}, WID=${work.wid}`); // 打印每个作品的 UID 和 WID
          return work.uid === uid && work.wid !== currentWid;
        })
        .map((work) => ({
          wname: work.wname,
          introduction: work.introduction,
          image: work.wimage || 'default-image.jpg', // 使用默认图片
        }));

      console.log('过滤后的其他作品:', otherWorks.value); // 调试输出
    } else {
      console.error("API 响应结构不符合预期");
    }
  } catch (error) {
    console.error('获取其他作品信息时出错:', error);
  }
};

const getShortIntroduction = (introduction) => {
  if (introduction.length > 20) {
    return introduction.slice(0, 20) + '...';
  }
  return introduction;
};




// 解码 Unicode 的函数并去除空段落，同时省略三分之二内容并在结尾添加省略号
// const decodeUnicode = (str) => {
//   try {
//     const decodedString = JSON.parse(`"${str}"`);
//     const parser = new DOMParser();
//     const doc = parser.parseFromString(decodedString, 'text/html');
//     let content = doc.body.innerHTML;

//     content = content.replace(/<p>(\s|<br>|&nbsp;)*<\/p>/g, '');

//     const unwrappedTextIndex = decodedString.indexOf('</p>') + 4;
//     if (unwrappedTextIndex < decodedString.length) {
//       const unwrappedText = decodedString.substring(unwrappedTextIndex).trim();
//       if (unwrappedText) {
//         content += `<p>${unwrappedText}</p>`;
//       }
//     }

//     const paragraphs = content.split('</p>');
//     const numToKeep = Math.ceil(paragraphs.length / 3);
//     const truncatedContent = paragraphs.slice(0, numToKeep).join('</p>') + '</p>';
//     return truncatedContent + '<p>...</p>';
//   } catch (error) {
//     console.error('解码 wddata 时出错:', error);
//     return '';
//   }
// };

//获取用户信息
const userInfo = ref({});
const fetchWriterInfo = async () => {
  // 判断是否已经登录
  if (localStorage.getItem('token') === null || localStorage.getItem('token') === '') {
    console.log('未登录');
    // 弹出提示框
    await ElMessageBox.alert('请先登录', '提示', {
      confirmButtonText: '确定',
      type: 'warning',
    });
    router.push('/login');
    return;
  }
  try {
    const response = await axios.post(`http://localhost:8080/user/getUserById/${uid.value}`,null, {
        headers: {
          Authorization: 'Bearer ' + getToken(),
        }
      }
    );
    userInfo.value = response.data.data;
    console.log('获取用户信息成功：', JSON.stringify(userInfo.value, null, 2));

    console.log(luid.value);
    
    //获取当前日期
    const currentDate = new Date();
    //初始化创建日期
    const udate = new Date(userInfo.value.udate);
    console.log(udate);
    //计算天数
    const day = Math.floor((currentDate - udate) / (1000 * 60 * 60 * 24));
    console.log(currentDate);
    days.value = day;
    console.log(days);
    
  } catch (error) {
    console.error('Error fetching user info:', error);
  }
};


const scriptTypes = ref([]);
const fetchScriptTypes = async (wid) => {
  try {
    const response = await axios.get(`http://localhost:8080/api/getworklabelByWid/${wid}`);
    scriptTypes.value = response.data.data;
  } catch (error) {
    console.error('Error fetching script types:', error);
  }
};

const imageBasePath = 'http://localhost:8080/api/images/';
const getImageUrl = (fileName) => fileName ? `${imageBasePath}${fileName}` : '0 (3).jpg';

const readScript = async () => {
  const id = route.params.id as string;
  if (id) {
    await router.push({ name: 'WorkView', params: { id } });
  }
};

const commentScript = () => {
  alert('发表评论！');
};

const buyRights = () => {
  if (localStorage.getItem('token')) {
    const id = route.params.id as string;

    router.push({ path: '/agreementview',query: { wid: id} })
    // await router.push({ name: 'WorkView', params: { id } },params: { id });

  } else {
    alert('请先登录！');
    router.push({ name: 'login' });
  }
};

const superviseScript = () => {
  alert('进行万众监督！');
};

onMounted(async () => {
  const wid = route.params.id as string;
  await getScriptInfo(wid);
  await fetchScriptTypes(wid);
  await fetchOtherWorks(wid);
  // 确保页面滚动到顶部
  window.scrollTo(0, 0);
  await fetchWriterInfo();
});
</script>



<template>
  <el-header class="header">
    <HeaderDemo />
  </el-header>
  <div class="work-profile">
    <div class="container">
      <div class="image-content">
        <div class="image-container">
          <el-image :src="getImageUrl(workimg)" fit="cover" class="cover-image"></el-image>
        </div>
        <div class="info-container">
          <h1>{{ title }}</h1>
          <p><strong>编剧：</strong> {{ playwright }}</p>
          <p><strong>标签：</strong>{{ scriptTypes.map(scriptType => scriptType.bname).join('、') }}</p>
          <p><strong>作者意愿：</strong> {{ authorIntent }}</p>
          <p><strong>编剧简介：</strong>
            {{ playwrightBio.length > 20 ? playwrightBio.slice(0, 20) + '...' : playwrightBio }}
          </p>

          <div class="timi">
            <p>更新时间：{{ updateTime }}</p>
          </div>

          <div class="buttons">
            <button @click="readScript">开始阅读</button>
            <button @click="commentScript">发表评论</button>
            <button @click="buyRights">版权购买</button>
            <button @click="superviseScript">万众监督</button>
          </div>
        </div>

        <!-- 添加垂直虚线的容器 -->
        <div class="vertical-line"></div>
        <div class="profile-container">
          <img :src="getImageUrl(userInfo.headlmg)" alt="头像" class="avatar">
          <p class="username">{{ playwright }}</p>
          <!-- <p class="user-level">阅文集团 Lv.5 作家</p> -->

          <div class="statistics-container">
            <div class="stat-item">
              <p class="stat-title">作品总数</p>
              <p class="stat-value">{{ totalWorksCount }}</p>
            </div>
            <div class="stat-item">
              <p class="stat-title">累计字数</p>
              <p class="stat-value">{{ totalWordsCount }}</p>
            </div>
            <div class="stat-item">
              <p class="stat-title">创作天数</p>
              <p class="stat-value">{{ days }}</p>
            </div>
          </div>
        </div>



      </div>
    </div>

    <!-- 编剧简介卡片 -->
    <div class="card-container">
      <div class="card">
        <h2>作品信息/内容</h2>
        <hr class="dashed-line">
        <p>{{ synopsis }}</p>
        <hr class="dashed-line">
        <p v-html="wddataContent" class="content-paragraph"></p>
        <button @click="readScript" class="buttons">后续内容</button>
        <!-- 使用 v-html 绑定解码后的作品内容 -->
      </div>
      <div class="side-card">
        <h2>作者其他作品</h2>
        <hr class="dashed-line">
        </hr>
        <div class="side-card-content" v-for="otherWork in otherWorks" :key="otherWork.wid"
          @click="navigateToWork(otherWork.wid)" style="cursor: pointer;">
          <el-image :src="getImageUrl(otherWork.wimage)" fit="cover" class="side-card-image"></el-image>
          <div class="side-card-text">
            <p>{{ otherWork.wname }}</p>
            <p>{{ getShortIntroduction(otherWork.introduction) }}</p>
          </div>
        </div>

      </div>
    </div>
    <FooterComp />
  </div>
</template>


<style scoped>
.header {
  position: relative;
  /* 或者不设置 position */
  background-color: #151313;
  height: 80px;
  z-index: 10;
  
  /* 确保在其他元素之上 */
}

.work-profile {

  max-width: 100%;
  padding-top: 20px;
  flex-wrap: nowrap;
  /* 不允许换行 */
  background: linear-gradient(to bottom, #e5e7e7, #fffbf1);
  /* 古风渐变背景 */
}


.container {
  width: 90%;
  height: 350px;
  margin: 1px auto;
  /* 增加左边的外边距，将整个容器向右移动 */
  padding: 20px;
  border: 1px solid #ffffff;
  border-radius: 8px;
  background-color: #ffffff;
  background: linear-gradient(135deg, #fffff3, #ffffff);
  /* 古风渐变背景 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.image-content {
  width: calc(100% - 20px);
  display: flex;
  align-items: stretch;
  /* 让子元素高度匹配父元素 */
  gap: 20px;
  /* 控制各部分之间的间距 */
}

.vertical-line {
  width: 3px;
  /* 线的宽度 */
  background-color: #f1f1f1;
  /* 线的颜色 */
  align-self: stretch;
  /* 让垂直线高度与父元素一致 */
}

.profile-container {
  display: flex;
  margin-left: 160px;
  flex-direction: column;
  align-items: center;
  /* 居中对齐 */
  margin-top: 20px;
}

.avatar {
  width: 100px;
  /* 头像宽度 */
  height: 100px;
  /* 头像高度 */
  border-radius: 50%;
  /* 圆形头像 */
  margin-top: 10px;
  transition: border-radius 0.3s ease;
}

.avatar:hover {
  border-radius: 10px;
  /* 悬停时变成圆角正方形 */
}

.username {
  font-size: 24px;
  color: #333;
  margin-top: 10px;
  font-family: 'Microsoft YaHei', sans-serif;
  font-weight: bold;
}

.user-level {
  font-size: 16px;
  color: #666;
  margin-top: 5px;
}

.statistics-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  /* 确保统计项均匀分布 */
  max-width: 300px;
  /* 设置容器宽度 */
  margin-top: 15px;
  text-align: center;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  /* 居中对齐每个统计项 */
  margin: 0 10px;
  /* 每个统计项之间的间距 */
}

.stat-title {
  font-size: 14px;
  color: #666;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-top: 5px;
  /* 与标题之间的间距 */
}


.image-container {
  width: 250px;
  height: 300px;
  background-color: #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info-container {
  font-size: 20px;
  color: #333;
  display: flex;
  flex-direction: column;
}

.info-container h1 {
  font-size: 35px;
  color: #333;
  margin-bottom: 10px;
  font-family: 'Microsoft YaHei', sans-serif;
  /* 使用微软雅黑 */
  font-weight: bold;
  /* 加粗 */
}

.info-container p {
  margin: 8px 0;
  line-height: 1.1;
  font-family: 'Microsoft YaHei', sans-serif;
  /* 使用微软雅黑 */
}

.card-container {
  display: flex;
  flex-wrap: nowrap;
  /* 确保子元素不会换行 */
  gap: 40px;
  /* 设置卡片之间的间距 */
  margin: 10px auto;
  width: 100%;
  /* 容器宽度 */
  justify-content: center;
  /* 保证卡片在窗口变化时居中 */
}

/* 新增的卡片样式 */
.card {
  width: 1000px;
  /* 设置固定的宽度 */
  min-width: 60%;
  padding: 15px;
  margin: 0 auto;
  /* 将卡片水平居中 */
  margin-left: 10%;
  /* 设置固定的左边距 */
  background: linear-gradient(to bottom, #fffff3, #f1ebd7);
  /* 古风渐变背景 */
  border: 1px solid #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);

}


.content-paragraph p {
  margin: 0 !important;
  /* 强制去掉每个段落的上下间距 */
  padding: 0 !important;
  line-height: 1.5;
  /* 如果需要更紧凑的行高，可以设置小一些 */
}

.card p {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
  font-family: 'Microsoft YaHei', sans-serif;
  /* 使用微软雅黑 */
}

.side-card {
  flex: 0 0 360px;
  /* 固定宽度，不会变形 */
  height: auto;
  /* 高度自动适应内容 */
  padding: 15px;
  background: linear-gradient(to bottom, #fbfcfc, #fffbf1);
  border: 1px solid #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  /* 可选，确保内容排列良好 */
  flex-direction: column;
  /* 纵向排列 */
  margin-right: 100px;
  /* 增加右边的外边距，设置间隔为20px */
  flex-shrink: 0;
}


.side-card h2 {
  font-family: 'Arial', 'Helvetica', sans-serif;
  /* 更改为圆润的无衬线字体 */
  font-weight: 600;
  /* 可选，使字体更粗一些 */
  font-size: 1.4em;
  /* 调整字体大小 */
  color: #333;
  /* 设置字体颜色 */
  margin-bottom: 10px;
  /* 添加一些底部间距 */
}

.side-card-content {
  width: 90%;
  height: 130px;
  display: flex;
  /* 使用 Flexbox */
  align-items: center;
  margin-bottom: 16px;
  /* 设置作品之间的间隔 */
  padding: 6px;
  /* 可选，增加一些内部间距 */
  /*border: 1px solid #e8e8e8;  可选，为每个作品添加边框 */
  border-radius: 10px;
  /* 可选，增加圆角效果 */
  background-color: #ffffff;
}

.side-card-content:hover {
  background-color: #f5f5f5;
  /* 悬停时的背景颜色 */
  /*border-color: #ccc;  悬停时的边框颜色 */
}

.side-card-image {
  width: 70%;
  /* 根据需要调整宽度 */
  height: 100%;
  margin-left: 15px;
  /* 根据需要调整高度 */
  margin-right: 10px;
  /* 图片和文本之间的间距 */
}

.side-card-text {
  display: flex;
  flex-direction: column;
  /* 使文字在垂直方向排列 */
}

.card h2 {
  font-size: 30px;
  color: #333;
  margin-bottom: 10px;
  font-family: 'Microsoft YaHei', sans-serif;
  /* 使用微软雅黑 */
  /*font-weight: bold;  加粗 */
}

.timi {
  font-size: 15px;
  color: #828080;
  margin-bottom: 10px;
  font-family: 'Microsoft YaHei', sans-serif;
  /* 使用微软雅黑 */
}

.buttons {
  display: flex;
  gap: 15px;
  margin-top: 1px;
}

button {
  padding: 15px 20px;
  background-color: transparent;
  /* 背景透明 */
  border: 1px solid rgb(146, 170, 244);
  /* 蓝色边框 */
  color: rgb(161, 175, 199);
  /* 蓝色文字 */
  font-size: 16px;
  font-weight: bold;
  /* 加粗文字 */
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

button:hover {
  background-color: #d1f2f6;
  /* 悬停时蓝色背景 */
  color: rgb(161, 175, 199);
  /* 悬停时文字白色 */
}

button:active {
  background-color: #86d1e8;
  /* 点击时更深的蓝色背景 */
  color: white;
  transform: translateY(2px);
  /* 点击时下沉效果 */
}

.dashed-line {
  border: none;
  border-top: 2px dashed #ccc;
  /* 设置虚线样式和颜色 */
  color: #fff;
  background-color: #fff;
  height: 1px;
  margin: 20px 0;
  /* 控制上下间距 */
}

/* //以下为设置富文本的样式 */
/* .ql-align-center{
    background-color: #9bde14;
} */

.content-paragraph>>>html,
.content-paragraph>>>body,
.content-paragraph>>>div,
.content-paragraph>>>ul,
.content-paragraph>>>li,
.content-paragraph>>>h1,
.content-paragraph>>>h2,
.content-paragraph>>>h3,
.content-paragraph>>>h4,
.content-paragraph>>>h5,
.content-paragraph>>>h6,
.content-paragraph>>>p,
.content-paragraph>>>ol,
.content-paragraph>>>pre {
    margin: 0;
    padding: 0;
    margin-bottom: 30px;
    font-weight: normal;
}

.content-paragraph>>>p {
    /* 设置行间距 */
    line-height: 30px;
}

.content-paragraph>>>u {
    text-decoration: underline;
    /*下划线*/
}

.content-paragraph>>>s {
    text-decoration: line-through;
    /*删除线*/
}

.content-paragrapht>>>p {
    white-space: pre-wrap;
    /*保留换行符*/
    word-wrap: break-word;
    /*自动换行*/
}

.content-paragraph>>>body {
    padding: 20px;
}

.content-paragraph>>>strong {
    font-weight: bold;
}

.content-paragraph>>>.ql-align-center {
    text-align: center;
}

.content-paragraph>>>.ql-align-right {
    text-align: right;
}

.content-paragraph>>>.ql-align-justify {
    text-align: justify !important;
    /*文本两端对齐*/
}

.content-paragraph>>>.ql-align-justify em {
    text-align: justify !important;
    background-color: #9bde14;
    /*文本两端对齐*/
}

</style>